<template>
  <div class="container">
    <div class="upload-container">
      <el-upload
        ref="uploadImage"
        :action="uploadUrl"
        drag
        list-type="picture"
        :auto-upload="false"
        :limit="1"
        :on-preview="handlePreview"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :http-request="upload"
        :before-upload="beforeUpload"
        v-if="checkPermi(['file:image:compress'])">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能压缩jpg/png文件，且不超过6M</div>
      </el-upload>
      <el-upload v-else drag action="https://jsonplaceholder.typicode.com/posts/" disabled>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能压缩jpg/png文件，且不超过6M</div>
      </el-upload>

      <el-divider></el-divider>

      <div class="file-compress">
        <div>压缩后文件大小不超过(kb)：</div>
        <el-input-number v-model="desFileSize" :min="1" size="small"></el-input-number>
      </div>
      <div class="file-compress">
        <div>递归压缩的比率(建议小于0.9)：</div>
        <el-input-number v-model="accuracy" :precision="2" :step="0.1" :min="0.1" size="small"></el-input-number>
      </div>

      <el-button v-if="this.file != null" type="primary" class="compress-btn" @click="compress">开始压缩</el-button>
    </div>

    <div class="result" v-if="compressedUrl">
      <div class="block">
        <span class="demonstration">原图片({{ srcSize }}kb)</span>
        <el-image class="re-image" :src="curUrl" :preview-src-list="srcList"></el-image>
      </div>
      <div class="block">
        <div class="download">
          压缩后({{ compressSize }}kb)
          <a class="down-link" :href="compressedUrl" :download="fileName">下载</a>
        </div>
        <el-image class="re-image" :src="compressedUrl" :preview-src-list="srcList"></el-image>
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="curUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { compressImage } from "@/api/file/compress"
import { checkPermi } from "@/utils/permission" // 权限判断函数

export default {
  name: "Compress",
  data() {
    return {
      uploadUrl: "http://localhost:8999/tduck-api/compress/image",
      file: null,
      compressedUrl: "",
      curUrl: "",
      dialogVisible: false,
      formData: new FormData(),
      srcList: [],
      desFileSize: 30,
      accuracy: 0.6,
      fileName: "",
      srcSize: null,
      compressSize: null,
    }
  },
  methods: {
    checkPermi,
    beforeUpload(file) {
      this.srcSize = Math.ceil(file.size / 1024)
      this.formData.append("file", file)
      const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png"
      const isLt2M = file.size / 1024 / 1024 < 6

      if (!isJPGOrPNG) {
        this.$message.error("压缩图片只能是 JPG/PNG 格式!")
      }
      if (!isLt2M) {
        this.$message.error("压缩图片大小不能超过 6MB!")
      }
      return isJPGOrPNG && isLt2M
    },
    upload() {
      this.formData.append("desFileSize", this.desFileSize)
      this.formData.append("accuracy", this.accuracy)
      compressImage(this.formData).then((data) => {
        this.compressSize = Math.ceil(data.size / 1024)
        let blob = new Blob([data])
        let url = window.URL.createObjectURL(blob)
        this.compressedUrl = url
        let splits = this.file.name.split(".")

        this.file = null

        this.srcList.push(this.curUrl)
        this.srcList.push(this.compressedUrl)

        this.fileName = splits[0] + "_compressed." + splits[1]
      })
    },
    compress() {
      this.$refs.uploadImage.submit()
    },
    handlePreview(file) {
      this.curUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file) {
      this.file = file
      this.curUrl = file.url
      this.compressedUrl = ""
      this.srcList = []
    },
    handleRemove() {
      this.formData = new FormData()
      this.compressedUrl = ""
      this.file = null
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: row;
  align-items: center;
  align-content: center;
  justify-content: center;
  margin-top: 20px;
}
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.compress-btn {
  margin-top: 10px;
}
.compressed {
  margin-left: 50px;
}
.file-compress {
  font-size: 14px;
  color: #303133;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}
.result {
  width: 460px;
  height: 220px;
  padding: 15px;
  margin-left: 60px;
  border: 1px solid #ebebeb;
  border-radius: 3px;
  transition: 0.2s;
  display: flex;
  flex-direction: row;
  justify-content: center;
  .block {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.block:nth-child(1) {
  border-right: 1px solid #eff2f6;
  padding-right: 30px;
}
.block:nth-child(2) {
  padding-left: 30px;
}

.re-image {
  width: 150px;
  height: 150px;
  margin-top: 10px;
}

.down-link {
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
  margin-left: 5px;
}
</style>
